<?php

namespace app\health\model;

use think\Model;
use think\model\relation\BelongsTo;

/**
 * 站点轮播图模型
 */
class HealthUserTask extends Model
{
    // 表名
    protected $name = 'health_user_task';

    protected $type = [
        'task_category' => 'integral',
        'award_type'    => 'integral',
        'status'        => 'integral',
        'receive'       => 'integral',
    ];

    /**
     * 关联任务信息
     * @return BelongsTo
     */
    public function task(): BelongsTo
    {
        return $this->belongsTo(HealthWebsiteTask::class, 'task_id');
    }

    /**
     * 获取用户任务完成信息
     * @param $userId
     * @return array[]
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public static function getCompleteInfo($userId): array
    {
        $data       = [
            'complete_task' => [],
            'receive_task'  => [],
            'receive_to_id' => [],
        ];
        $doTask     = self::where('user_id', $userId)
            ->where('status', '1')
            ->select();
        $total      = 0;
        $awardValue = 0;
        foreach ($doTask as $row) {
            ++$total;
            if ($row->award_type === 1) {
                $awardValue = bcadd($awardValue, $row->award_value, 2);
            }
            if ($row->task_category === 3 || (date('Y-m-d', $row->complete_time) === date('Y-m-d') && $row->task_category === 1) || (date('Y-m', $row->complete_time) === date('Y-m') && $row->task_category === 2)) {
                if ($row['receive'] === 1) {
                    $data['complete_task'][] = $row->task_id;
                } else {
                    $data['receive_task'][]               = $row->task_id;
                    $data['receive_to_id'][$row->task_id] = $row->id;
                }
            }
        }
        $data['tips'] = "已完成{$total}个任务，累计获得{$awardValue}元";
        return $data;
    }
}
